package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.DishDto;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

  @Autowired
  private DishFlavorService dishFlavorService;

  @Autowired
  private DishService dishService;

    @Override
    public void add(DishDto dishDto) {
        Dish dish = new Dish();
        //将dishDto中的菜品信息保存到dish表中
        BeanUtils.copyProperties(dishDto,dish);
        //调用方法添加菜品
        dishService.save(dish);
        //菜品信息存储之后就会自动生成dishId
        //获取口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置口味表中对应的dishId
            flavor.setDishId(dish.getId());
            dishFlavorService.save(flavor);
        }
    }

    @Override
    public void updateByIdWithDishFlavor(DishDto dishDto) {
        //修改菜品的信息
        Dish dish = new Dish();
        //将修改的菜品信息copy到菜品表中
        BeanUtils.copyProperties(dishDto,dish);
        //调用方法保存到菜品表中
        dishService.updateById(dish);
        //获取菜品id对应的口味信息
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        //查询dish_id的口味
        queryWrapper.eq("dish_id",dish.getId());
        //删除之前的口味
        dishFlavorService.remove(queryWrapper);
        //获取添加的口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
            dishFlavorService.save(flavor);
        }
    }
}
